import 'package:shared_preferences/shared_preferences.dart';
import 'package:meePet/utils/LogUtils.dart';

///键值存储工具类(这里使用mmkv实现)
class SPUtil {
  static SharedPreferences? _mmkv;

  ///搞个int方法让他尽快获取实例(实例是异步获取的，会有非常小的时间差)
  static init(){
    _getMMKV();
  }


  static SharedPreferences? _getMMKV() {
    if(_mmkv==null){
      LogUtils.i("初始化SP开始:${DateTime.timestamp()}");
      SharedPreferences.getInstance().then((value) => {
        _dealWithGetInstance(value)
      });
      return _mmkv;
    }else{
      return _mmkv!;
    }
  }

  static _dealWithGetInstance(SharedPreferences value){
    LogUtils.i("已获得SP实例");
    _mmkv=value;
    LogUtils.i("初始化SP结束:${DateTime.timestamp()}");
  }

  static void save(String key, String value) {
    _getMMKV()?.setString(key, value);
  }

  ///dart 中long对应也是int类型
  static void saveInt(String key, int value) {
    _getMMKV()?.setInt(key, value);
  }

  ///dart 中没有float对应也是double类型
  static void saveDouble(String key, double value) {
    _getMMKV()?.setDouble(key, value);
  }

  static void saveBool(String key, bool value) {
    _getMMKV()?.setBool(key, value);
  }

  static String load(String key, {String defaultValue = ""}) {
    LogUtils.i("加载key:" + key);
    String str;
    try {
      str = _getMMKV()?.getString(key) ?? defaultValue;
    } catch (e, stack) {
      LogUtils.i("加载key错误:" + stack.toString());
      str = defaultValue;
    }

    return str;
  }

  static int loadInt(String key, {int defaultValue = 0}) {
    return _getMMKV()?.getInt(key)??defaultValue;
  }

  static double loadDouble(String key, {double defaultValue = 0}) {
    return _getMMKV()?.getDouble(key)??defaultValue;
  }

  static bool loadBool(String key, {bool defaultValue = false}) {
    return _getMMKV()?.getBool(key)??defaultValue;
  }
}
